package com.yzh.wanandroid.component.fragment

import android.view.KeyEvent
import android.view.View
import android.widget.LinearLayout
import androidx.navigation.fragment.navArgs
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.yzh.core.navigation.NavHostFragment
import com.yzh.wanandroid.R
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.callback.FragmentKeyDownListener
import com.yzh.wanandroid.component.activity.MainActivity
import com.yzh.wanandroid.databinding.FragmentWebInfoBinding
import com.yzh.wanandroid.vm.WebInfoFragmentVm

/**
 * web详情页
 */
class WebInfoFragment : MvvmFragment<FragmentWebInfoBinding, WebInfoFragmentVm>(),
    FragmentKeyDownListener {

    private val TAG = "WebInfoFragment"

    override fun getLayoutId() = R.layout.fragment_web_info

    override fun initViewModel(): WebInfoFragmentVm = createViewModel()

    private val args: WebInfoFragmentArgs by navArgs()

    private lateinit var agentWeb: AgentWeb

    override fun initView(view: View) {
        initTitleBar()
        initAgentWeb()
    }

    /**
     *  初始化titleBar
     */
    private fun initTitleBar() {
        mBinding.run {
            webInfoTitleLayout.titleText.text = args.webTitle
            webInfoTitleLayout.toolbar.navigationIcon =
                requireActivity().getDrawable(R.drawable.arrow_back)
            webInfoTitleLayout.toolbar.setNavigationOnClickListener {
                onBackPressed()
            }
        }
    }

    /**
     * 初始化AgentWeb
     */
    private fun initAgentWeb() {
        mBinding.run {
            agentWeb = AgentWeb.with(requireActivity())
                .setAgentWebParent(webRoot, LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
                .interceptUnkownUrl()
                .createAgentWeb()
                .ready()
                .go(args.webUrl)
        }
    }


    override fun initData() {
        initActivityListener()
    }

    private fun onBackPressed() {
        if (!agentWeb.back()) {
            requireActivity().onBackPressed()
        }
    }

    private fun initActivityListener() {
        (activity as MainActivity).setFragmentKeyDownListener(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        (activity as MainActivity).clearKeyDownListener()
    }

    /**
     * fragment 事件返回监听
     */
    override fun onKeyDown(host: NavHostFragment, keyCode: Int, event: KeyEvent): Boolean {
        for (fragment in host.childFragmentManager.fragments) {
            if (fragment is WebInfoFragment && agentWeb.back()) {
                return true
            }
        }
        return false
    }
}